/**
* Copyright 2013 nabla
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
*/
package com.nabla.wapp.report.shared.parameter;

import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;

import com.google.gwt.user.client.rpc.IsSerializable;


public class ParameterList extends LinkedList<ParameterGroup> implements IsSerializable {

	private static final long serialVersionUID = 1L;

	public ParameterList() {}	// for serialization only

	public void addNameToSet(final Set<String> names) {
		for (ParameterGroup p : this)
			p.addNameToSet(names);
	}

	public RemoveParameterStatus removeParameter(final Set<String> names) {
		RemoveParameterStatus status = RemoveParameterStatus.NOP;
		final Iterator<ParameterGroup> iter = this.iterator();
		while (iter.hasNext()) {
			switch (iter.next().removeParameter(names)) {
			case SUCCESS:
				iter.remove();
				status = isEmpty() ? RemoveParameterStatus.SUCCESS : RemoveParameterStatus.SUCCESS_NOT_EMPTY;
				break;
			case SUCCESS_NOT_EMPTY:
				status = RemoveParameterStatus.SUCCESS_NOT_EMPTY;
				break;
			default:
			case NOP:
				break;
			}
		}
		return status;
	}

	public void consolidateParameters() {
		int n = size();
		if (n > 1) {
			for (int i = 0; i < (n-1); ++i) {
				final ParameterGroup gi = get(i);
				final Set<String> names = new HashSet<String>();
				gi.addNameToSet(names);
				int titleCount = 0;
				for (int j = n - 1; j > i; --j) {
					final ParameterGroup gj = get(j);
					final RemoveParameterStatus status = gj.removeParameter(names);
					if (status == RemoveParameterStatus.NOP)
						continue;
					if (titleCount < 1)
						gi.setPrompt(gj.getPrompt() + "\n" + gj.getPrompt());
					else if (titleCount == 1)
						gi.setPrompt(gi.getPrompt() + "\n...");
					++titleCount;
					if (status == RemoveParameterStatus.SUCCESS)
						this.remove(j);
				}
			}
		}
	}
}
